import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/model/partner_ship_pay_model.dart';
import 'package:flutter_app_unionad/request/partner_ship_request.dart';
import 'package:flutter_app_unionad/ui/basice/base_navigation_widget.dart';
import 'package:core_package/core_package.dart';
import 'package:flutter_app_unionad/ui/basice/input_separator_widget.dart';
import 'package:flutter_app_unionad/ui/basice/my_button.dart';
import 'package:flutter_app_unionad/ui/basice/select_sex_widget.dart';
import 'package:flutter_app_unionad/ui/my_facility/widget/select_pay_type_widget.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart';

//加入合伙人
class JoinPartnershipPage extends StatefulWidget {
  static const String routeName = "/joinPartnershipPage";

  @override
  _JoinPartnershipPageState createState() => _JoinPartnershipPageState();
}

class _JoinPartnershipPageState extends State<JoinPartnershipPage> {
  String? name;

  // int sex;
  String? idCode;
  String? phone;
  String? address;

  String number = "0";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    thirdPayListen();
  }

  @override
  Widget build(BuildContext context) {
    return BaseNavigationWidget(
      needScrollView: true,
      title: "加入合伙人",
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(
              horizontal: 40.px,
              vertical: 40.px,
            ),
            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(5.px)),
            child: buildTopContent(),
          ),
          MySizeBox(height: 10),
          Container(
            padding: EdgeInsets.symmetric(
              horizontal: 40.px,
              vertical: 40.px,
            ),
            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(5.px)),
            child: buildBottomContent(),
          ),
        ],
      ),
    );
  }

  Widget buildBottomContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "购买设备",
          style: TextStyle(
            color: MyColors.formHex("#272727FF"),
            fontSize: MyFont.font16,
            fontWeight: MyFontWeight.bold,
          ),
        ),
        MySizeBox(height: 20),
        InputSeparatorWidget(
          controller: TextEditingController(text: number),
          valueChange: (value) {
            setState(() {
              number = value;
            });
          },
          title: "购买",
          placeholder: "请输入购买设备数量，最多20台",
          keyboard: TextInputType.number,
          titleWidth: 60,
          icon: Text(
            "${Configuration().price}元/台",
            style: TextStyle(
              color: MyColors.color_27_27_27,
              fontSize: MyFont.font13,
              fontWeight: MyFontWeight.regular,
            ),
          ),
        ),
        MySizeBox(height: 55),
        Center(
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                "需要购买更多设备，",
                style: TextStyle(
                  color: MyColors.formHex("#A0A0A0FF"),
                  fontSize: MyFont.font13,
                  fontWeight: MyFontWeight.regular,
                ),
              ),
              GestureDetector(
                onTap: () {
                  //
                  callService();
                },
                child: Text(
                  "点击联系客服专员",
                  style: TextStyle(
                    decoration: TextDecoration.underline,
                    color: MyColors.formHex("#737373FF"),
                    fontSize: MyFont.font13,
                    fontWeight: MyFontWeight.regular,
                  ),
                ),
              )
            ],
          ),
        ),
        MySizeBox(height: 20),
        Center(
          child: MyButton(
            title: "支付（${number.stringIsEmpty ? "0" : int.parse(number) * int.parse(Configuration().price)}元）",
            onTap: () {
              payOnTap();
            },
          ),
        ),
      ],
    );
  }

  Widget buildTopContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "基本信息",
          style: TextStyle(
            color: MyColors.formHex("#272727FF"),
            fontSize: MyFont.font16,
            fontWeight: MyFontWeight.bold,
          ),
        ),
        MySizeBox(height: 20),
        InputSeparatorWidget(
          title: "姓名",
          placeholder: "请输入姓名",
          valueChange: (value) => name = value,
          controller: TextEditingController(text: name),
        ),
        // MySizeBox(height: 10),
        // SelectSexWidget(sex: sex, selectSexOnTap: (sex) => sex = sex),
        MySizeBox(height: 10),
        InputSeparatorWidget(
          title: "身份证",
          placeholder: "请输入身份证",
          keyboard: TextInputType.visiblePassword,
          valueChange: (value) => idCode = value,
          controller: TextEditingController(text: idCode),
          maxLength: 18,
        ),
        MySizeBox(height: 10),
        InputSeparatorWidget(
          title: "联系电话",
          placeholder: "请输入联系电话",
          valueChange: (value) => phone = value,
          keyboard: TextInputType.number,
          maxLength: 11,
          controller: TextEditingController(text: phone),
        ),
        MySizeBox(height: 10),
        InputSeparatorWidget(
          title: "联系地址",
          placeholder: "请输入联系地址",
          valueChange: (value) => address = value,
          controller: TextEditingController(text: address),
        ),
        MySizeBox(height: 10),
      ],
    );
  }

  void callService() {
    Configuration().call();
  }

  void payOnTap() async {
    if (name == null || name!.stringIsEmpty) {
      ShowToastWidget.showToast(msg: '姓名不能为空');
      return;
    }
    if (idCode == null || idCode!.stringIsEmpty) {
      ShowToastWidget.showToast(msg: '身份证不能为空');
      return;
    }
    if (!verifyCardId(idCode!)) {
      ShowToastWidget.showToast(msg: '身份证格式不对');
      return;
    }
    if (phone == null || phone!.stringIsEmpty) {
      ShowToastWidget.showToast(msg: '电话不能为空');
      return;
    }
    if (!isPhoneString(phone)) {
      ShowToastWidget.showToast(msg: '电话格式不对');
      return;
    }
    if (address == null || address!.stringIsEmpty) {
      ShowToastWidget.showToast(msg: '地址不能为空');
      return;
    }
    if (number.stringIsEmpty) {
      ShowToastWidget.showToast(msg: '购买数量不能为空');
      return;
    }
    if (int.parse(number) > int.parse(Configuration().maxCount)) {
      ShowToastWidget.showToast(msg: '购买数量不能大于${Configuration().maxCount}');
      return;
    }
    ProgressDialog.showProgress(context);
    PartnerShipRequest.savePartnerShipRequest(address: address, idNo: idCode, name: name, mobile: phone).then((value) {
      ProgressDialog.dismiss(context);
      if (mounted) {
        ShowBottomAlertDialog.showBottomDialog(context, height: 168.px + SizeFill.statusHeight!, builder: (ctx) {
          return SelectPayTypeWidget(
            weChatPayOnTop: () {
              selectPay("1");
            },
            alipayPayOnTop: () {
              selectPay("2");
            },
          );
        });
      }
    });
  }

  void selectPay(String pay) {
    print("开始支付$pay");
    ProgressDialog.showPayFirstLoading(context);
    PartnerShipRequest.partnerShipPayRequest(num: number, payType: pay).then((value) {
      ProgressDialog.dismiss(context);
      if (value != null) {
        if (pay == '1') {
          //微信支付
          payThird(value, 0);
        } else {
          //支付宝
          payThird(value, 1);
        }
      }
    });
  }

  void payThird(PartnerShipPayModel orderModel, int type) async {
    if (type == 0) {
      //微信支付

      final future = await payWithWeChat(
        appId: orderModel.appId!,
        partnerId: orderModel.partnerid!,
        prepayId: orderModel.prepayid!,
        packageValue: orderModel.package!,
        nonceStr: orderModel.nonceStr!,
        timeStamp: int.parse(orderModel.timeStamp!),
        sign: orderModel.paySign!,
      );
      print(future);
      if (!future) {
        ShowToastWidget.showToast(msg: "支付失败");
      }
    } else if (type == 1) {
      //支付宝支付
      print("支付宝支付 ---$orderModel");
      tobias.aliPay(orderModel.payInfo!).then((value) {
        print(value["resultStatus"]);
        if (value["resultStatus"] == "9000") {
          Navigator.pop(context, true);
          ShowToastWidget.showToast(msg: '支付成功');
        } else {
          ShowToastWidget.showToast(msg: value["memo"]);
        }
      });
    }
  }

//微信支付监听
  void thirdPayListen() async {
    weChatResponseEventHandler.listen((res) {
      if (res is WeChatPaymentResponse) {
        print(res.errCode);
        if (res.errCode == 0) {
          //支付成功
          Navigator.pop(context, true);

          ShowToastWidget.showToast(msg: '支付成功');
        } else {
          ShowToastWidget.showToast(msg: res.errStr == null || res.errStr!.length == 0 ? "支付失败" : res.errStr!);
        }
      }
    });
//    _pay = _alipay.payResp().listen(_listenPay);
  }
}
